using Dapper;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;
using Microsoft.Data.SqlClient;

namespace Lzfy_Refund_Service.Repositories
{
    public class PatientInfoRepository : IPatientInfoRepository
    {
        private readonly IDbConnectionFactory _connectionFactory;
        private readonly ILogger<PatientInfoRepository> _logger;

        public PatientInfoRepository(IDbConnectionFactory connectionFactory, ILogger<PatientInfoRepository> logger)
        {
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public async Task<PatientInfo?> GetPatientInfoByIdAsync(string patientId)
        {
            try
            {
                using var connection = _connectionFactory.CreateConnection();
                
                var sql = $@"
                    SELECT tb1.name AS Name, 
                           tb1.sex AS Sex, 
                           tb1.date_of_birth AS DateOfBirth, 
                           tb1.id_number AS IdNumber, 
                           tb1.phone_number AS PhoneNumber, 
                           tb1.patient_id AS PatientId, 
                           tb1.balance AS Balance 
                    FROM OPENQUERY(HIS, 
                        'select t1.name, 
                                decode(t1.sex_code, ''1'', ''男'', ''2'', ''女'') as sex, 
                                to_char(t1.date_of_birth,''yyyy-mm-dd'') as date_of_birth, 
                                t1.id_number, 
                                t1.phone_number1 as phone_number, 
                                t1.patient_id, 
                                t3.balance 
                         from pca.pca_patient_info t1 
                         join pca.pca_prepay_account_index t2 
                           on t1.patient_id = t2.patient_id 
                         join pca.pca_prepay_account_master t3 
                           on t2.account_index = t3.account_index 
                          and t3.account_type = ''O'' 
                         where t1.patient_id = ''{patientId}''') tb1";

                var result = await connection.QueryFirstOrDefaultAsync<PatientInfo>(sql);
                
                _logger.LogInformation($"查询患者信息: {patientId}, 结果: {(result != null ? "找到" : "未找到")}");
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询患者信息失败: {patientId}");
                throw;
            }
        }
    }
}